/*
 * @Author: yuanxiaohu
 * @Date: 2025-06-15 16:55:17
 * @LastEditors: yuanxiaohu
 * @LastEditTime: 2025-06-19 21:42:58
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \wine-trend-hui-18\cloudfunctions\getFootMark\checkExistAndUpdate\index.js
 */
// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
    try {
        // 存储数据
        const { type, data } = event
        const { _openid, goodsId, ...rest } = data

        // 日期格式化
        function formatTime(date) {
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            const hours = String(date.getHours()).padStart(2, '0')
            const minutes = String(date.getMinutes()).padStart(2, '0')
            const seconds = String(date.getSeconds()).padStart(2, '0')
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
        }
        const now = formatTime(new Date())
        const res = await db.collection('footMarkList')
            .where({
                _openid,
                goodsId
            })
            .limit(1)
            .get()

        if (res.data.length > 0) {
            // 2. 已存在，更新 viewTime
            await db.collection('footMarkList').doc(res.data[0]._id).update({
                data: {
                    viewTime: now
                }
            })

            return {
                code: 200,
                msg: '更新成功',
                updated: true
            }
        } else {
            await db.collection('footMarkList').add({
                data: {
                    _openid,
                    goodsId,
                    ...rest,
                    viewTime: now,
                    createTime: now,
                }
            })

            return {
                code: 200,
                msg: '新增成功',
                updated: false
            }

        }

    } catch (err) {
        console.error('足迹处理异常:', err)
        return {
            code: 500,
            message: '服务器异常',
            error: err.message
        }
    }
}